<template>
  <div class="app-container search-list">
    <table-pagination
        :expand="true"
        :showOperatingButton="true"
        ref="el-search-table"
        :fetch="getData"
        type="remote"
        :adaptive="fixOption"
        :page-sizes="[20, 50, 100]"
        :columns="columns"
        :form-options="formOptions"
        list-field="records"
        total-field="totalElements"
        page-index-key="page"
        page-size-key="pageSize"
        height="300"
        method="get">
      <template slot="button">
        <div style="display: flex;align-items: flex-start">
          <el-button type="primary" size="mini" @click="settingVisible = true">导出订单</el-button>
        </div>
      </template>
    </table-pagination>
    <el-dialog :visible.sync="settingVisible" title="订单导出" width="400px">
      <div class="desc">
        <div class="export" style="text-align: left;">
          <header>导出范围</header>
          <section>
            <div class="orca-row orca-form-item">
              <el-radio v-model="exportType" label="all" style="margin-bottom: 15px">所有订单</el-radio>
              <el-radio v-model="exportType" label="filter">符合当前筛选条件的订单</el-radio>
            </div>
          </section>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="handleExport" :loading="submitLoading">
            {{submitLoading ? '导出中': '导出'}}
          </el-button>
          <el-button @click="settingVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import TablePagination from '_c/Tables/table-pagination';
import {getOrderPage, getAllOrderPage} from '@/api/order';
import {currency, utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';
import axios from 'axios';

export default {
    name: 'order-list',
    components: {TablePagination},
    data () {
        return {
            submitLoading: false,
            exportType: 'all',
            settingVisible: false,
            fixOption: {fixedHeader: true},
            timeZone: '+8',
            formParams: {
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: '',
                page: 1,
                pageSize: 20
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                submitBtnText: '查询',
                size: 'small',
                labelWidth: 120,
                resetBtnCallback: () => {
                    this.formParams = {...this.formParams,
                        ...{
                            status: '',
                            payStatus: '',
                            logisticsStatus: '',
                            orderNumber: '',
                            email: '',
                            startTime: '',
                            endTime: '',
                            page: 1,
                            pageSize: 20
                        }};
                    this.timeZone = '+8';
                    this.$refs['el-search-table'].resetFields();
                    this.$refs['el-search-table'].fetchHandler(this.formParams, false);
                },
                forms: [
                    {prop: 'orderNumber', label: '订单号：', placeholder: '请输入订单号'},
                    {
                        prop: 'timeZone',
                        label: '时区选择：',
                        itemType: 'select',
                        placeholder: '请选择时区',
                        options: [
                            {value: '', label: '北京时间（UTC+8）'},
                            {value: '-5', label: '美东时间（UTC-5）'}],
                        selectChange: (e, params) => {
                            this.$nextTick(() => {
                                this.timeZone = e || '+8';
                                this.$refs['el-search-table'].fetchHandler({...this.formParams, timeZone: this.timeZone}, false);
                            });
                        }
                    },
                    {
                        prop: ['startTime', 'endTime'],
                        label: '支付时间：',
                        itemType: 'daterange',
                        startPlaceholder: ' 开始日期',
                        endPlaceholder: ' 结束日期'
                    }
                ]
            },
            columns: []
        };
    },
    methods: {
        storeMap (type) {
            // console.log(type);
            const status = new Map([
                ['待发货', 'warning'],
                ['待收货', 'primary'],
                ['已完成', 'success'],
                ['全部发货', 'info'],
                ['全部确认', 'success']
            ]);
            return status.get(type);
        },
        getData: function (params) {
            params.timeZone = params.timeZone || '+8';
            console.log(params.startTime);
            params.startTime = this.getSiteTimeZoneStartTime(params.startTime, params.timeZone);
            params.endTime = this.getSiteTimeZoneEndTime(params.endTime, params.timeZone);
            params.status = this.formParams.status;
            this.columns = [{
                label: '订单号',
                prop: 'orderNumber'
            },
            {
                label: '订单金额',
                prop: 'payAmount',
                render: row => {
                    if (row.payAmount) {
                        return currency(row.payAmount, '$');
                    }
                    return '';
                }
            },
            {
                label: '支付时间' + (this.timeZone === '+8' ? '（UTC+8）' : '（UTC-5）'),
                prop: 'paymentTime',
                render: row => {
                    return utcFormat(row.paymentTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                }
            },
            {label: '域名', prop: 'domain'}];
            this.formParams = {...this.formParams, ...params};
            return new Promise((resolve, reject) => {
                getAllOrderPage(this.formParams).then((res) => {
                    resolve(res);
                });
            });
        },
        handleDetail (id) {
            this.$router.push({name: 'order-detail', params: {id}});
        },
        getSiteTimeZoneStartTime (startTime, timeZone) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            console.log(timeZone);
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + timeZone;
            console.log(new Date(timeZoneStr));
            return new Date(timeZoneStr).getTime();
        },
        getSiteTimeZoneEndTime (endTime, timeZone = 8) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + timeZone;
            return new Date(timeZoneStr).getTime();
        },
        downloadURL (data) {
            const blob = new Blob([data], { type: 'application/vnd.ms-excel' });
            console.log(blob);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '订单列表' + '_' + '_' + new Date().getTime().toString() + (Math.random().toFixed(2) * 400 + 100).toString() + '.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        handleExport () {
            this.submitLoading = true;
            let params = {};
            params = this.exportType === 'all' ? params : Object.assign(params, this.formParams);
            axios({
                method: 'get',
                params,
                url: this.exportPath,
                headers: {
                    'X-TULIANG-Session-Token': getToken()
                },
                responseType: 'arraybuffer'
            }).then(res => {
                this.downloadURL(res.data);
                this.submitLoading = false;
            }).catch(() => {
                this.$message.error('导出失败');
                this.submitLoading = false;
            });
        },
        handleResponse (response, file, fileList) {
            // this.pageParams.page = 1;
            // this.getData(this.pageParams);
            return response;
        }
    },
    computed: {
        exportPath () {
            return `${process.env.VUE_APP_BASE_API}/manager/order/export`;
        }
    }
};
</script>

<style scoped lang="scss">
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}
.desc{
  font-size: 14px;
  color: #7e849c;
  margin-bottom: 0;
  .export {
    position: relative;
    header {
      padding-bottom: 20px;
      font-size: 16px;
      color: #30354d;
    }
    .orca-row{
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
